package org.hsieh.tr.explore.ui.actions.dbview;

import java.sql.Connection;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.dialogs.InputDialog;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.window.Window;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.actions.ActionFactory.IWorkbenchAction;
import org.hsieh.tr.explore.ExplorerActivator;
import org.hsieh.tr.explore.TransactionExplorerPreperencePage;
import org.hsieh.tr.explore.exception.ExceptionHandler;
import org.hsieh.tr.explore.ui.console.TextResultConsole;
import org.hsieh.tr.explore.util.ApplicationUtil;
import org.hsieh.tr.explore.util.JFaceUtil;
import org.hsieh.tr.explore.util.StringUtil;

import cutenimy.co.cc.hsqlmock.HSQLFacade;
import cutenimy.co.cc.hsqlmock.HSQLRunningException;


public class CreateHSQLDatabaseaAction extends Action implements
		IWorkbenchAction {
	public CreateHSQLDatabaseaAction() {
		super();
		setText("Create HSQL database");
	}

	@Override
	public void run() {
		String location = ExplorerActivator
				.getDefault()
				.getPreferenceStore()
				.getString(TransactionExplorerPreperencePage.HSQL_DATA_LOCATION);
		String database = null;
		if (StringUtil.isNullOrEmpty(location)) {
			MessageDialog
					.openError(
							PlatformUI.getWorkbench()
									.getActiveWorkbenchWindow().getShell(),
							"HSQL database",
							"Please set the HSQL data location before you create a HSQL database at Preference page.");
			return;
		}

		InputDialog dialog = new InputDialog(JFaceUtil.getPlatformShell(),
				"HSQL database creator", "Please give the database name", "",
				null);
		if (dialog.open() == Window.OK) {
			try {
				HSQLFacade facade = new HSQLFacade(location);
				database = dialog.getValue();
				if (StringUtil.isNullOrEmpty(database)) {
					MessageDialog
							.openError(PlatformUI.getWorkbench()
									.getActiveWorkbenchWindow().getShell(),
									"HSQL database",
									"You don't give correct database name or the database name is empty.");
					return;
				}
				Connection start = facade.start(database);
				if (start != null) {
					TextResultConsole.console("Create database'" + database
							+ "' successfully");
					activeConsoleView();
				}
			} catch (HSQLRunningException e) {
				ExceptionHandler.promptError("Can't create database '"
						+ database + " ' at '" + location + "'", e);
			}
		}
	}

	private void activeConsoleView() {
		ApplicationUtil.activeView("org.eclipse.ui.console");
	}

	public void dispose() {

	}

}
